﻿using System;
using System.Collections.Generic;
using System.Web.Mvc;
using MugenInjection.Infrastructure;
using MugenInjection.Interface;

namespace MugenInjection.Web.Mvc
{
    /// <summary>
    ///     A DataAnnotationsModelValidatorProvider implementation that injects the validators.
    /// </summary>
    public class MugenInjectionDataAnnotationsModelValidatorProvider : DataAnnotationsModelValidatorProvider
    {
        #region Fields

        private readonly IInjector _injector;

        #endregion

        #region Constructors

        /// <summary>
        ///     Initializes a new instance of the <see cref="MugenInjectionDataAnnotationsModelValidatorProvider" /> class.
        /// </summary>
        public MugenInjectionDataAnnotationsModelValidatorProvider(IInjector injector)
        {
            Validate.ArgumentNotNull(injector, "injector");
            _injector = injector;
        }

        #endregion

        #region Overrides of DataAnnotationsModelValidatorProvider

        /// <summary>
        ///     Gets a list of validators.
        /// </summary>
        /// <returns>
        ///     A list of validators.
        /// </returns>
        /// <param name="metadata">The metadata.</param>
        /// <param name="context">The context.</param>
        /// <param name="attributes">The list of validation attributes.</param>
        protected override IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata, ControllerContext context,
                                                                     IEnumerable<Attribute> attributes)
        {
            IEnumerable<ModelValidator> validators = base.GetValidators(metadata, context, attributes);
            if (validators == null)
                return null;
            foreach (ModelValidator attribute in validators)
            {
                ModelValidator attr = attribute;
                _injector.Inject(ref attr);
            }
            return validators;
        }

        #endregion
    }
}